package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTester {
    private static final ReentrantLock REENTRANT_LOCK = new ReentrantLock(false);

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new TestLockImpl()).start();
        }
        if (!REENTRANT_LOCK.tryLock()) {
            System.err.println("Can't get lock!");
        } else {
            System.err.println("Get lock!");
            REENTRANT_LOCK.unlock();
        }
    }

    public static void testLock(Long id) {
        REENTRANT_LOCK.lock();
        try {
            System.err.println("Task ID:" + id);
            System.err.println("To Sleep");

            TimeUnit.SECONDS.sleep(5);

            System.err.println("Wake up");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            REENTRANT_LOCK.unlock();
        }
    }

    static class TestLockImpl implements Runnable {
        @Override
        public void run() {
            testLock(Thread.currentThread().getId());
        }
    }
}